<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Material;

class SyncOAMaterial extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'csw:SyncOAMaterial';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * The app to wechat
     */
    protected $app;

    /**
     * Create a new command instance.
     *
     */
    public function __construct()
    {
        parent::__construct();
        $this->app = app('wechat.official_account');
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info('csw:SyncOAMaterial start!');

        //$this->app->base->clearQuota();
        $this->listMaterial('image', 0, 20);
        //$this->listMaterial('video', 0, 20);
        //$this->listMaterial('voice', 0, 20);
        //$this->listMaterial('news', 0, 20);

        $this->info('csw:SyncOAMaterial end!');
    }

    public function listMaterial($type, $offset, $count)
    {
        $list = $this->app->material->list($type, $offset, $count);
        if (!$list && !isset($list['total_count']) && !$list['total_count'] && !isset($list['item']) && !$list['item']) {
            $this->info($type. ' not find!');
            return false;
        } else {
            foreach ($list['item'] as $row) {
                Material::firstOrCreate(
                    ['type' => $type, 'media_id' => $row['media_id']],
                    ['name' => $row['name'], 'update_time' => $row['update_time'], 'url' => $row['url']]
                );
            }

            if ($list['total_count'] > $offset + $count) {
                return true;
            }

            return false;
        }
    }
}
